package com.spider.moudle.factory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadFactory;

public class NamedThreadFactory implements ThreadFactory {

    private String localName;

    private String info;

    private String factoryName;

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public Thread newThread(Runnable r) {
        Thread thread=new Thread(r,takeName());
        return thread;
    }

    public String getLocalName() {
        return localName;
    }

    public void setLocalName(String localName) {
        this.localName = localName;
    }

    public NamedThreadFactory(String localName) {
        this.localName = localName;
    }

    private String takeName(){
        String ts=formatter.format(new Date());
        String name="";
        if(info==null){
            if(factoryName!=null){
                name="factory-"+factoryName+"-thread-{ts:"+System.currentTimeMillis()+",site:'"+localName+"',time:'"+ts+"'}";
            }else {
                name="thread-{ts:"+System.currentTimeMillis()+",site:'"+localName+"',time:'"+ts+"'}";
            }
        }else {
            if(factoryName!=null){
                name="factory-"+factoryName+"-thread-{ts:"+System.currentTimeMillis()+",site:'"+localName+"',time:'"+ts+"',info:'"+info+"'}";
            }else {
                name="thread-{ts:"+System.currentTimeMillis()+",site:'"+localName+"',time:'"+ts+"',info:'"+info+"'}";
            }
        }
        return name;
    }

    public NamedThreadFactory(String localName, String info) {
        this.localName = localName;
        this.info = info;
    }

    public String getFactoryName() {
        return factoryName;
    }

    public void setFactoryName(String factoryName) {
        this.factoryName = factoryName;
    }
}
